package com.cy.dda.service.collection.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cy.dda.comm.utils.CommonUtils;
import com.cy.dda.dao.mapper.cases.CasesMapper;
import com.cy.dda.dao.mapper.collection.CollectionRecordAttachmentMapper;
import com.cy.dda.dao.mapper.collection.CollectionRecordMapper;
import com.cy.dda.dao.mapper.collection.RepayRecordMapper;
import com.cy.dda.model.PageBean;
import com.cy.dda.model.ao.collection.CollectionRecordAddAO;
import com.cy.dda.model.ao.collection.CollectionRecordAttachmentAddAO;
import com.cy.dda.model.ao.collection.CollectionRecordEditAO;
import com.cy.dda.model.domain.cases.Cases;
import com.cy.dda.model.domain.collection.CollectionRecord;
import com.cy.dda.model.domain.collection.CollectionRecordAttachment;
import com.cy.dda.model.domain.collection.RepayRecord;
import com.cy.dda.model.enums.cases.CasesEndStatus;
import com.cy.dda.model.enums.cases.CasesStatus;
import com.cy.dda.model.enums.collection.RepayStatus;
import com.cy.dda.model.enums.collection.RepayType;
import com.cy.dda.model.query.collection.CollectionRecordListAdminQuery;
import com.cy.dda.model.query.collection.CollectionRecordListQuery;
import com.cy.dda.model.vo.collection.CollectionRecordAllListVO;
import com.cy.dda.model.vo.collection.CollectionRecordAttachmentVO;
import com.cy.dda.model.vo.collection.CollectionRecordDetailInfoAdminVO;
import com.cy.dda.model.vo.collection.CollectionRecordDetailInfoVO;
import com.cy.dda.model.vo.collection.CollectionRecordListAdminVO;
import com.cy.dda.model.vo.collection.CollectionRecordListVO;
import com.cy.dda.model.vo.statistics.StatisticsCollectionRecordVO;
import com.cy.dda.service.BaseService;
import com.cy.dda.service.collection.CollectionRecordService;

import lombok.extern.slf4j.Slf4j;

/**
 * 催收记录 CollectionRecordService
 *
 * @author: tanyilin
 * @create: 2018年11月2日 下午4:09:23
 */
@Slf4j
@Service
public class CollectionRecordServiceImpl extends BaseService implements CollectionRecordService {

	@Autowired
	private CollectionRecordMapper collectionRecordMapper;
	@Autowired
	private CollectionRecordAttachmentMapper collectionRecordAttachmentMapper;
	@Autowired
	private RepayRecordMapper repayRecordMapper;
	@Autowired
	private CasesMapper casesMapper;
	
	
	@Override
	@Transactional
	public void addCollectionRecord(CollectionRecordAddAO addAO, Long userId) {
		
		//初始各个值
		Date time = new Date();
		Long casesId = addAO.getCasesId();
		Long orgId = 0L;
		Long customerId = 0L;
		Long collectionRecordId = 0L;
		
		//先查询cases是否存在
		Cases dbCases = new Cases();
		dbCases.setId(casesId);
		if(!CommonUtils.isEmpty(userId)) {
			dbCases.setUserId(userId);
		}
		dbCases = casesMapper.selectOne(dbCases);
		state(dbCases != null, "委案信息异常");
		//得到客户ID、委托机构ID、催收员ID
		customerId = dbCases.getCustomerId();
		orgId = dbCases.getOrgId();
		userId = dbCases.getUserId();
		
		//新增催收记录
		CollectionRecord collectionRecord = new CollectionRecord();
		BeanUtils.copyProperties(addAO, collectionRecord);
		collectionRecord.setCasesId(casesId);
		collectionRecord.setOrgId(orgId);
		collectionRecord.setCustomerId(customerId);
		collectionRecord.setUserId(userId);
		collectionRecord.setCreateTime(time);
		collectionRecord.setUpdateTime(time);
		collectionRecordMapper.insertSelective(collectionRecord);
		//得到催收记录ID
		collectionRecordId = collectionRecord.getId();
		
		//新增回款记录
		if(!RepayType.NON_REPAY.equals(addAO.getRepayType())) {
			RepayRecord repayRecord = new RepayRecord();
			BeanUtils.copyProperties(addAO, repayRecord);
			repayRecord.setCollectionRecordId(collectionRecordId);
			repayRecord.setCasesId(casesId);
			repayRecord.setOrgId(orgId);
			repayRecord.setCustomerId(customerId);
			repayRecord.setUserId(userId);
			repayRecord.setRepayType(addAO.getRepayType());
			repayRecord.setRepayStatus(RepayStatus.CONFIRM_WAIT);
			repayRecord.setCreateTime(time);
			repayRecord.setUpdateTime(time);
			repayRecordMapper.insertSelective(repayRecord);
		}
		
		//新增催收记录-附件信息
		List<CollectionRecordAttachmentAddAO> attachmentList = addAO.getAttachmentList();
		if(!CommonUtils.isEmpty(attachmentList)) {
			//构造新增的list
			List<CollectionRecordAttachment> attachmentDoAddList = new ArrayList<>();
			for(CollectionRecordAttachmentAddAO tempAddAO : attachmentList) {
				CollectionRecordAttachment collectionRecordAttachment = new CollectionRecordAttachment();
				BeanUtils.copyProperties(tempAddAO, collectionRecordAttachment);
				collectionRecordAttachment.setCollectionRecordId(collectionRecordId);
				collectionRecordAttachment.setName("");
				collectionRecordAttachment.setCreateTime(time);
				collectionRecordAttachment.setUpdateTime(time);
				attachmentDoAddList.add(collectionRecordAttachment);
			}
			//批量新增处理
			collectionRecordAttachmentMapper.insertBatch(attachmentDoAddList);
		}
		
		//判断是否申请结案
		if(addAO.isApplyEndCases()) {
			//更新委案状态、委案结束状态、委案结束类型
			int result = 1;
			result = casesMapper.updateCasesStatus(casesId, CasesStatus.END_WAIT, time);
			state(result == 1, "更新委案状态异常");
			
			result = casesMapper.updateCasesEndStatus(casesId, CasesEndStatus.CONFIRM_WAIT, time);
			state(result == 1, "更新委案结束状态异常");
			
			result = casesMapper.updateCasesEndType(casesId, addAO.getCasesEndType(), time);
			state(result == 1, "更新委案结束类型异常");
		}
		
		//更新委案更新时间
		Cases updateCases = new Cases();
		updateCases.setId(casesId);
		updateCases.setUpdateTime(time);
		casesMapper.updateByPrimaryKeySelective(updateCases);
		
	}


	@Override
	public PageBean<CollectionRecordListAdminVO> selectCollectionRecordListAdmin(CollectionRecordListAdminQuery query) {
		
		if(query.getCollectionRecordStartTime() != null) {
            query.setCollectionRecordStartTime(CommonUtils.getDayStartTime(query.getCollectionRecordStartTime()));
        }
        if(query.getCollectionRecordEndTime() != null) {
            query.setCollectionRecordEndTime(CommonUtils.getDayEndTime(query.getCollectionRecordEndTime()));
        }
		
		int total = collectionRecordMapper.selectCollectionRecordListAdminCount(query);
		List<CollectionRecordListAdminVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = collectionRecordMapper.selectCollectionRecordListAdmin(query);
			list.stream().forEach(c -> {
				c.setCasesTypeText(c.getCasesType().getText());
				c.setCasesStatusText(c.getCasesStatus().getText());
				c.setCollectionRecordTypeText(c.getCollectionRecordType().getText());
				c.setRepayTypeText(c.getRepayType().getText());
			});
		}
		return new PageBean<CollectionRecordListAdminVO>(list, total);
	}


	@Override
	public CollectionRecordDetailInfoAdminVO selectCollectionRecordDetailInfoAdminVO(Long collectionRecordId) {
		
		CollectionRecordDetailInfoAdminVO modelVo = collectionRecordMapper.selectCollectionRecordDetailInfoAdminVO(collectionRecordId);
		state(modelVo != null, "催收日志信息异常");
		modelVo.setCollectionRecordTypeText(modelVo.getCollectionRecordType().getText());
		modelVo.setRepayTypeText(modelVo.getRepayType().getText());
		if(modelVo.getRepayWay() != null) {
			modelVo.setRepayWayText(modelVo.getRepayWay().getText());
		}
		
		//查询该回款信息对应的催收记录的上传的附件信息
		List<CollectionRecordAttachmentVO> attachmentList = collectionRecordAttachmentMapper.selectAttachmentBycollectionRecordId(collectionRecordId);
		if(!CommonUtils.isEmpty(attachmentList)) {
			modelVo.setAttachmentList(attachmentList);
		}

		return modelVo;
	}


	@Override
	public PageBean<CollectionRecordListVO> selectCollectionRecordList(CollectionRecordListQuery query) {
		int total = collectionRecordMapper.selectCollectionRecordListCount(query);
		List<CollectionRecordListVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = collectionRecordMapper.selectCollectionRecordList(query);
			list.stream().forEach(c -> {
				c.setCollectionRecordTypeText(c.getCollectionRecordType().getText());
				c.setRepayTypeText(c.getRepayType().getText());
			});
		}
		return new PageBean<CollectionRecordListVO>(list, total);
	}

	@Override
	public PageBean<CollectionRecordAllListVO> selectCollectionRecordAllList(CollectionRecordListQuery query) {
		int total = collectionRecordMapper.selectCollectionRecordListCount(query);
		List<CollectionRecordListVO> tempDataList = new ArrayList<>();
		List<CollectionRecordAllListVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			tempDataList = collectionRecordMapper.selectCollectionRecordList(query);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			tempDataList.stream().forEach(c -> {
				c.setCollectionRecordTypeText(c.getCollectionRecordType().getText());
				c.setRepayTypeText(c.getRepayType().getText());
				c.setCreateMonthStr(sdf.format(c.getCreateTime()));
			});
			//按照月份进行分组
			Map<String, List<CollectionRecordListVO>> map = tempDataList.stream().collect(Collectors.groupingBy(CollectionRecordListVO::getCreateMonthStr));
			map.entrySet().stream().forEach(m -> {
				CollectionRecordAllListVO collectionRecordAllListVO = new CollectionRecordAllListVO();
				try {
					collectionRecordAllListVO.setMonth(sdf.parse(m.getKey()));
				} catch (ParseException e) {
					log.error("催收日期月份转换格式异常", e);
				}
				collectionRecordAllListVO.setMonthStr(m.getKey());
				collectionRecordAllListVO.setDataList(m.getValue());
				list.add(collectionRecordAllListVO);
			});
			
			//按照月份进行排序
			Collections.sort(list, new Comparator<CollectionRecordAllListVO>() {

				@Override
				public int compare(CollectionRecordAllListVO o1, CollectionRecordAllListVO o2) {
				
					return o2.getMonth().compareTo(o1.getMonth());
				}
			});
			
			list.stream().forEach(c -> {
				c.setMonth(null);
			});
		}
		
		return new PageBean<CollectionRecordAllListVO>(list, total, tempDataList.size());
	}

	@Override
	public List<StatisticsCollectionRecordVO> selectStatisticsCollectionRecordVO(Long userId, int n) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		List<StatisticsCollectionRecordVO> newList = new ArrayList<>();
		Date endDate = new Date();
		Date startDate = CommonUtils.addTime(endDate, 1 - n, Calendar.DAY_OF_YEAR);
		startDate = CommonUtils.getDayStartTime(startDate);
		endDate = CommonUtils.getDayEndTime(endDate);
		List<StatisticsCollectionRecordVO> oldList = collectionRecordMapper.selectStatisticsCollectionRecordVO(userId, startDate, endDate);
		int num = CommonUtils.isEmpty(oldList) ? 0 : oldList.size();
		int temp = 0;
		
		for(int i = 0; i < n; i++) {
			if(temp < num) {
				if(startDate.compareTo(oldList.get(temp).getDate()) < 0) {
					//填充空数据
					StatisticsCollectionRecordVO vo = new StatisticsCollectionRecordVO();
					vo.setCount(0);
					vo.setDateFormatStr(sdf.format(startDate));
					newList.add(vo);
				}else if(startDate.compareTo(oldList.get(temp).getDate()) == 0) {
					//相等的时候，直接放进newList
					StatisticsCollectionRecordVO vo = oldList.get(temp);
					vo.setDateFormatStr(sdf.format(vo.getDate()));
					vo.setDate(null);
					newList.add(vo);
					//下标往前推移
					temp++;
				}
			}else if(temp >= num && startDate.compareTo(endDate) <= 0) {
				// 填补空数据
				StatisticsCollectionRecordVO vo = new StatisticsCollectionRecordVO();
				vo.setCount(0);
				vo.setDateFormatStr(sdf.format(startDate));
				newList.add(vo);
			}
			//日期往下一天推移
			startDate = CommonUtils.addTime(startDate, 1, Calendar.DAY_OF_YEAR);
		}
		
		return newList;
	}


	@Override
	public CollectionRecordDetailInfoVO selectCollectionRecordDetailInfoVO(Long collectionRecordId) {
		
		CollectionRecordDetailInfoAdminVO modelVo = collectionRecordMapper.selectCollectionRecordDetailInfoAdminVO(collectionRecordId);
		state(modelVo != null, "回款信息异常");
		modelVo.setCollectionRecordTypeText(modelVo.getCollectionRecordType().getText());
		modelVo.setRepayTypeText(modelVo.getRepayType().getText());
		if(modelVo.getRepayWay() != null) {
			modelVo.setRepayWayText(modelVo.getRepayWay().getText());
		}
		
		//查询该回款信息对应的催收记录的上传的附件信息
		List<CollectionRecordAttachmentVO> attachmentList = collectionRecordAttachmentMapper.selectAttachmentBycollectionRecordId(collectionRecordId);
		if(!CommonUtils.isEmpty(attachmentList)) {
			modelVo.setAttachmentList(attachmentList);
		}
		
		CollectionRecordDetailInfoVO detailInfoVO = new CollectionRecordDetailInfoVO();
		BeanUtils.copyProperties(modelVo, detailInfoVO);
		
		return detailInfoVO;
	}


	@Override
	@Transactional
	public void doEdit(CollectionRecordEditAO editAO) {
		
		Date time = new Date();
		Long collectionRecordId = editAO.getCollectionRecordId();
		Long repayRecordId = editAO.getRepayRecordId();
		
		//更新催记信息
		CollectionRecord updateCr = new CollectionRecord();
		BeanUtils.copyProperties(editAO, updateCr);
		updateCr.setId(collectionRecordId);
		updateCr.setUpdateTime(time);
		collectionRecordMapper.updateByPrimaryKeySelective(updateCr);
		
		//更新回款信息（如果原本就有回款记录）repayRecordId != null
		if(!CommonUtils.isEmpty(repayRecordId)) {
			
			RepayRecord updateRr = new RepayRecord();
			BeanUtils.copyProperties(editAO, updateRr);
			updateRr.setId(repayRecordId);
			updateRr.setUpdateTime(time);
			if(RepayType.NON_REPAY.equals(updateRr.getRepayType())) {
				updateRr.setAmount(BigDecimal.ZERO);
			}
			repayRecordMapper.updateByPrimaryKeySelective(updateRr);
			
		}else {
			//原本是没有回款记录，repayRecordId == null
			CollectionRecord dbCr = collectionRecordMapper.selectByPrimaryKey(collectionRecordId);
			if(!RepayType.NON_REPAY.equals(dbCr.getRepayType())) {
				//但是修改成'有回款'的情况，则需要新增一条回款记录
				RepayRecord insertRepayRecord = new RepayRecord();
				BeanUtils.copyProperties(editAO, insertRepayRecord);
				insertRepayRecord.setCollectionRecordId(dbCr.getId());
				insertRepayRecord.setCasesId(dbCr.getCasesId());
				insertRepayRecord.setOrgId(dbCr.getOrgId());
				insertRepayRecord.setCustomerId(dbCr.getCustomerId());
				insertRepayRecord.setUserId(dbCr.getUserId());
				insertRepayRecord.setRepayStatus(RepayStatus.CONFIRM_WAIT);
				insertRepayRecord.setCreateTime(time);
				insertRepayRecord.setUpdateTime(time);
				repayRecordMapper.insertSelective(insertRepayRecord);
			}
		}
		
		//更新催记-影音资料附件
		List<CollectionRecordAttachmentAddAO> attachmentList = editAO.getAttachmentList();
		if(!CommonUtils.isEmpty(attachmentList)) {
			//构造新增的list
			List<CollectionRecordAttachment> attachmentDoAddList = new ArrayList<>();
			for(CollectionRecordAttachmentAddAO tempAddAO : attachmentList) {
				CollectionRecordAttachment collectionRecordAttachment = new CollectionRecordAttachment();
				BeanUtils.copyProperties(tempAddAO, collectionRecordAttachment);
				collectionRecordAttachment.setCollectionRecordId(collectionRecordId);
				collectionRecordAttachment.setName("");
				collectionRecordAttachment.setCreateTime(time);
				collectionRecordAttachment.setUpdateTime(time);
				attachmentDoAddList.add(collectionRecordAttachment);
			}
			//批量新增处理
			collectionRecordAttachmentMapper.insertBatch(attachmentDoAddList);
			//删除无效数据
			collectionRecordAttachmentMapper.deleteByUpdateTime(collectionRecordId, time);
		}
		
		
	}


	
}
